package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.ChatRequestMessage;
import com.netty.chatRoom.message.ChatResponseMessage;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ChatRequestMessage chatRequestMessage) throws Exception {
        // 服务器获取到了客户端发送消息请求
        // 目标用户
        String to = chatRequestMessage.getTo();
        Channel toChannel = SessionFactory.getSession().getChannel(to);
        if (toChannel==null){// 目标用户不存在
            channelHandlerContext.writeAndFlush(new ChatResponseMessage(false,String.format("【%S】用户不存在",to)));
        }else {// 目标用户存在
            toChannel.writeAndFlush(new ChatResponseMessage(chatRequestMessage.getFrom(),chatRequestMessage.getContent()));
        }

    }
}
